<?php

namespace App\Exports;

use Maatwebsite\Excel\Concerns\FromCollection;

class UserExport implements FromCollection
{
    private $row;
    private $data;

    public function __construct($row,$data)
    {
        $this->row = $row;
        $this->data = $data;
    }
    /**
    * 过滤文本中的emoji表情包（输出到excel文件中会导致问题）
    * @param string $text 原文本
    * @return string 过滤emoji表情包后的文本
    */
    function removeEmoji($text){
        $len = mb_strlen($text);
        $newText = '';
        for($i=0;$i<$len;$i++){
            $str = mb_substr($text, $i, 1, 'utf-8');
            if(strlen($str) >= 4) continue;//emoji表情为4个字节
            $newText .= $str;
        }
        return $newText;
    }
    public function collection()
    {
        $row = $this->row;
        $data = $this->data;

        //设置表头
        foreach ($row[0] as $key => $value) {
            $key_arr[] = $key;
        }

        //输入数据
        foreach ($data as $key => &$value) {
            $js = [];
            for ($i=0; $i < count($key_arr); $i++) {
                $text = $this->removeEmoji($value[ $key_arr[$i] ]);
                $js = array_merge($js,[ $key_arr[$i] => $text ]);
            }
            array_push($row, $js);
            unset($val);
        }
        return collect($row);
    }
}